package repository

import (
	"context"
	"net/url"
	"server/components/models/ent"
	"server/components/models/ent/predicate"
	"server/components/models/ent/user"
)

type SearchAccountsRequest struct {
	SearchRequest
	FirstName *string
	LastName  *string
	Email     *string
}

func (s *SearchAccountsRequest) EnsureDefaults() {
	s.SearchRequest.EnsureDefaults()
}

func (s *SearchAccountsRequest) FromQuery(q *url.URL) error {
	if err := s.SearchRequest.FromQuery(q); err != nil {
		return err
	}
	if val := q.Query().Get("firstName"); val != "" {
		s.FirstName = &val
	}
	if val := q.Query().Get("lastName"); val != "" {
		s.LastName = &val
	}
	if val := q.Query().Get("email"); val != "" {
		s.Email = &val
	}
	return nil
}

func SearchAccounts(ctx context.Context, request SearchAccountsRequest) ([]*ent.User, error) {
	request.EnsureDefaults()
	query := EntClient().User.Query()
	predicates := make([]predicate.User, 0, 1)
	if request.FirstName != nil {
		predicates = append(predicates, user.FirstNameContainsFold(*request.FirstName))
	}
	if request.LastName != nil {
		predicates = append(predicates, user.LastNameContainsFold(*request.LastName))
	}
	if request.Email != nil {
		predicates = append(predicates, user.EmailContainsFold(*request.Email))
	}
	query = query.Where(user.And(predicates...)).Offset(request.From).Limit(request.Size)
	return query.All(ctx)
}
